package fido.torrentsite;

import fido.DefaultTorrentImpl;
import fido.FidoCommonUtils;
import fido.Torrent;
import org.apache.log4j.Logger;
import org.mymediadb.api.mmdb.model.Movie;

import java.text.MessageFormat;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class ThePirateBay implements TorrentSite {

    private static final Logger LOG = Logger.getLogger(ThePirateBay.class);
    //                                                                                 DetailsPage            Name                   MagnetLink                    Torrent                                   Seeders                              Leechers
    private static final String REGEX = "<td>.*?<div class=\\\"detName\\\"><a href=\\\"(.*?)\\\" class.*?\\\">(.*?)</a.*?<a href=\\\"(.*?)\\\" title.*?<a href=\\\"(.*?)\\\" title.*?<td align=\\\"right\\\">(.*?)</td>.*?<td align=\\\"right\\\">(.*?)</td>";
    private final int DETAILS_PAGE = 1;
    private final int NAME = 2;
//    private final int MAGNET_LINK = 3;
    private final int TORRENT = 4;
    private final int SEEDERS = 5;
    private final int LEECHERS = 6;
    private final Pattern pattern = Pattern.compile(REGEX, Pattern.DOTALL);
    private String searchUrl;


    public ThePirateBay() {

        FidoCommonUtils.loadAdditionalPropertiesFromFile(getTorrentSiteAlias());
        searchUrl = FidoCommonUtils.getPropertyValue(getTorrentSiteAlias() + ".searchurl");
        if (searchUrl.equals("")) {
            LOG.info("Setting up config for ThePirateBay");
            configTorrentSite();
            FidoCommonUtils.loadAdditionalPropertiesFromFile(getTorrentSiteAlias());
            searchUrl = FidoCommonUtils.getPropertyValue(getTorrentSiteAlias() + ".searchurl");
        }
    }

    public String getTorrentSiteAlias() {
        return "ThePirateBay";
    }

    private void configTorrentSite() {
        //This will install all settings needed for ThePirateBay
        //To its own settings file

        Properties pirateBayProperty = new Properties();
        //save search path to property
        pirateBayProperty.setProperty(getTorrentSiteAlias() + ".searchurl", "http://thepiratebay.org/search/{0}/0/7/207");
        // save this as a new settingsFile
        FidoCommonUtils.saveSettingsFile(getTorrentSiteAlias(), pirateBayProperty);
    }

    public Torrent search(Movie movie) {

        String movieName = FidoCommonUtils.prepareMovieNameForUrl(movie.getName(), "UTF-8");
        String newSearch = MessageFormat.format(searchUrl, movieName);
        String page = FidoCommonUtils.getWebPage(newSearch);

        Matcher m = pattern.matcher(page);
        DefaultTorrentImpl torrent;
        int torrentCounter = 0;
        while (m.find()) {
            torrentCounter++;
            try {
                torrent = new DefaultTorrentImpl();
                torrent.setDetailsPageUrl("http://thepiratebay.org" + m.group(DETAILS_PAGE));
                torrent.setName(m.group(NAME));
                torrent.setTorrentUrl(m.group(TORRENT));
                torrent.setSeeders(Integer.parseInt(m.group(SEEDERS)));
                torrent.setLeechers(Integer.parseInt(m.group(LEECHERS)));
                torrent.setTorrentSiteName(this.getTorrentSiteAlias());
                if (FidoCommonUtils.doesImdbIdExistsInTorrentDetails(torrent, movie.getImdbId())) {
                    LOG.debug("Found torrent IMDBId in details Page");
                    return torrent;
                }
                LOG.debug("Found torrent:" + torrent.getName() + " but imdbID didn't match");

            } catch (IndexOutOfBoundsException e) {
                LOG.info(e.toString());
                return null;
            }

        }
        if (torrentCounter == 0) {
            LOG.debug("No torrents found at all, There were no results on the search page?");
        } else {
            LOG.debug("Found " + torrentCounter + " torrents matching search name - but not ImdbID");
        }
        return null;
    }

    @Override
    public void configureWithGUI() {
        //No configuration is required
    }


    @Override
    public void configureWithTUI() {
        //No configuration is required
    }


    public boolean isConfigured() {
        return true;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public boolean equals(Object o) {
        if (o.getClass() != this.getClass()) {
            return false;
        }
        TorrentSite torrentSite = (TorrentSite) o;
        if (!torrentSite.getTorrentSiteAlias().equals(this.getTorrentSiteAlias())) {
            return false;
        }
        return true;
    }
}
